package com.heaton.videocar.core

import cn.com.heaton.blelibrary.ble.utils.ByteUtils
import com.easysocket.EasySocket
import com.easysocket.config.EasySocketOptions
import com.easysocket.entity.OriginReadData
import com.easysocket.entity.SocketAddress
import com.easysocket.interfaces.conn.ISocketActionListener
import com.easysocket.interfaces.conn.SocketActionListener
import com.easysocket.utils.LogUtil
import com.heaton.baselib.utils.LogUtils
import com.heaton.videocar.removeTimeout
import com.heaton.videocar.setTimeout


/**
 * author: jerry
 * date: 20-12-1
 * email: superliu0911@gmail.com
 * des:
 */
object SocketManager {


    const val TAG = "SocketManager"
    private var sendResultCallback: SendResultCallback?=null

    fun initSocket(){
        //socket配置
        val options = EasySocketOptions.Builder()
            .setSocketAddress(SocketAddress("192.168.4.1", 80)) //主机地址
            // 强烈建议定义一个消息协议，方便解决 socket黏包、分包的问题
//             .setReaderProtocol(DefaultMessageProtocol()) // 默认的消息协议
            .setMaxWriteBytes(12*1024)
            .build()

        EasySocket.getInstance().setDebug(false)

        //初始化EasySocket
        EasySocket.getInstance()
            .options(options) //项目配置
            .createConnection() //创建一个socket连接
            .subscribeSocketAction(socketActionListener)
            .connect()
    }

    fun connect(){
        EasySocket.getInstance().connect()
    }

    fun disconnect(){
        EasySocket.getInstance().disconnect(false)
    }

    fun sendData(data: ByteArray?, callback: SendResultCallback?=null){
        if (data != null){
            sendResultCallback = callback
            EasySocket.getInstance().upBytes(data)
            LogUtils.logi("$TAG>>>[sendData]: ${data.size}")
            setTimeout(10, 2000){
                sendResultCallback?.onResult(ByteArray(0))
            }
        }
    }

    interface SendCallback {
        fun onStart()
        fun onProgress(index: Int)
        fun onFinish()
        fun onError()
    }

    private val socketActionListener: ISocketActionListener = object : SocketActionListener() {
        /**
         * socket连接成功
         * @param socketAddress
         */
        override fun onSocketConnSuccess(socketAddress: SocketAddress) {
            super.onSocketConnSuccess(socketAddress)
            LogUtils.logi("$TAG>>>[onSocketConnSuccess]: ")
        }

        /**
         * socket连接失败
         * @param socketAddress
         * @param isNeedReconnect 是否需要重连
         */
        override fun onSocketConnFail(
            socketAddress: SocketAddress,
            isNeedReconnect: Boolean
        ) {
            super.onSocketConnFail(socketAddress, isNeedReconnect)
            LogUtils.logi("$TAG>>>[onSocketConnFail]: ")
        }

        /**
         * socket断开连接
         * @param socketAddress
         * @param isNeedReconnect 是否需要重连
         */
        override fun onSocketDisconnect(
            socketAddress: SocketAddress,
            isNeedReconnect: Boolean
        ) {
            super.onSocketDisconnect(socketAddress, isNeedReconnect)
            LogUtil.d("socket断开连接，是否需要重连：$isNeedReconnect")
        }

        /**
         * socket接收的数据
         * @param socketAddress
         * @param originReadData
         */
        override fun onSocketResponse(
            socketAddress: SocketAddress,
            originReadData: OriginReadData
        ) {
            super.onSocketResponse(socketAddress, originReadData)
            originReadData.bodyData?.also {
                LogUtils.logi("$TAG>>>[onSocketResponse]:${ByteUtils.toHexString(it)} ")
                //A: 1 传输命令有效 , 0 传输命令无效 , 2 空间不足,保存的数据无效 , 3 整个视频保存成功
                sendResultCallback?.onResult(it)
                removeTimeout(10)
            }
        }
    }

    object SendResult{
        const val COMMAND_VALID = 1
        const val COMMAND_INVALID = 0
        const val NOT_ENOUGH_SPACE = 2
        const val SAVE_SUCCESS = 3
    }

}